package com.zidian.teacher.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.zidian.teacher.R;
import com.zidian.teacher.adapter.EvaluateChartAdapter;
import com.zidian.teacher.adapter.EvaluateCustomAdapter;
import com.zidian.teacher.bean.EvaluateDetailBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

import com.zidian.teacher.bean.EvaluateCustomBean;
import com.zidian.teacher.bean.EvaluateDetaiChartBean;

public class EvaluateCustomFragment extends Fragment {
    private String weburl;
    private String channelName;
    boolean isLoading;
    private RecyclerView recyclerView;
    private RecyclerView customRecyclerView;
    private SwipeRefreshLayout swipeRefreshWidget;

    private List<EvaluateDetaiChartBean> evaluateSupervisorData = new ArrayList<>();
    private List<EvaluateDetaiChartBean> evaluateColleagueData = new ArrayList<>();
    private List<EvaluateDetaiChartBean> evaluateStudentData = new ArrayList<>();
    private List<EvaluateCustomBean.DataBean.ListBean> customData = new ArrayList<>();
    private EvaluateChartAdapter adapterEvalute;
    private EvaluateCustomAdapter adapterCustom;
    private Handler handler = new Handler();
    private EvaluateCustomBean.DataBean bean;
    private int startrow = 1;

    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (view == null) {//优化View减少View的创建次数


            if (channelName.equals("自定义评价")) {
                view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_evaluate_detail_custom, null,
                        false);
                customRecyclerView = (RecyclerView) view.findViewById(R.id.list);
                swipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);


                initViewCustom();
                getCustomData();
            } else {

                //该部分可通过xml文件设计Fragment界面，再通过LayoutInflater转换为View组件
                view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_evaluate_detail_chart, null,
                        false);
                recyclerView = (RecyclerView) view.findViewById(R.id.m_recycler);
                initView();
                initData();

            }

        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {//如果View已经添加到容器中，要进行删除，负责会报错
            parent.removeView(view);
        }
        return view;
    }

    @Override
    public void setArguments(Bundle bundle) {
        // TODO Auto-generated method stub
        weburl = bundle.getString("weburl");
        channelName = bundle.getString("name");

    }


    public void initView() {

        if (channelName.equals("学生评价")) {
            adapterEvalute = new EvaluateChartAdapter(getActivity(), evaluateStudentData);
        } else if (channelName.equals("督导评价")) {
            adapterEvalute = new EvaluateChartAdapter(getActivity(), evaluateSupervisorData);
        } else {
            adapterEvalute = new EvaluateChartAdapter(getActivity(), evaluateColleagueData);
        }


        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapterEvalute);


        //添加点击事件
        adapterEvalute.setOnItemClickListener(new EvaluateChartAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Log.d("test", "item position = " + position);
//                startActivity(InteractionAskDetailAct.class);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });


    }

    public void initData() {
        getEvaluate(weburl);
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                getData();
//            }
//        }, 1500);

    }

    /**
     * 获取测试数据
     */
    private void getEvaluateData(EvaluateDetailBean.DataBean model) {

        if (channelName.equals("学生评价")) {
            for (int i = 0; i < model.getName().size(); i++) {
                EvaluateDetaiChartBean bean = new EvaluateDetaiChartBean(Constant.pointBgColors[i], model.getName().get(i).getIndexscore(), model.getName().get(i).getIndexName(), model.getName().get(i).getTwoIndex());
                evaluateStudentData.add(bean);
            }
            adapterEvalute.notifyDataSetChanged();
        } else if (channelName.equals("督导评价")) {
            for (int i = 0; i < model.getName().size(); i++) {
                EvaluateDetaiChartBean bean = new EvaluateDetaiChartBean(Constant.pointBgColors[i], model.getName().get(i).getIndexscore(), model.getName().get(i).getIndexName(), model.getName().get(i).getTwoIndex());
                evaluateSupervisorData.add(bean);
            }
            adapterEvalute.notifyDataSetChanged();
        } else {
            for (int i = 0; i < model.getName().size(); i++) {
                EvaluateDetaiChartBean bean = new EvaluateDetaiChartBean(Constant.pointBgColors[i], model.getName().get(i).getIndexscore(), model.getName().get(i).getIndexName(), model.getName().get(i).getTwoIndex());
                evaluateColleagueData.add(bean);
            }
            adapterEvalute.notifyDataSetChanged();
        }
    }


    private void initViewCustom() {

        adapterCustom = new EvaluateCustomAdapter(getActivity(), customData, bean);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        customRecyclerView.setLayoutManager(layoutManager);
        customRecyclerView.setAdapter(adapterCustom);


        swipeRefreshWidget.setColorSchemeResources(R.color.colorAccent);
        swipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshWidget.setRefreshing(true);
            }
        });
        swipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        customData.clear();
                        startrow = 1;
                        getCourse(startrow + "");
                    }
                }, 2000);
            }
        });


        customRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapterCustom.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = swipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapterCustom.notifyItemRemoved(adapterCustom.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startrow++;
                                getCourse(startrow + "");
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });


    }


    private void getCustomData() {

        getCourse(startrow + "");

        adapterCustom.notifyDataSetChanged();
        adapterCustom.notifyItemRemoved(adapterCustom.getItemCount());
    }

    /**
     * 获取测试数据
     */
    private void getEvaluate(String weburl) {
        String loginUrl = Constant.URL_TEACHER + weburl;
        HashMap<String, String> map = new HashMap<>();
        map.put("teacherId", GetUserInfo.getTeacherId(getActivity()));
        map.put("token", GetUserInfo.getToken(getActivity()));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                if (swipeRefreshWidget != null) {
                    swipeRefreshWidget.setRefreshing(false);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (swipeRefreshWidget != null) {
                    swipeRefreshWidget.setRefreshing(false);
                }
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(getActivity(), jsonObject.getString("message"));
                        return;
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                EvaluateDetailBean model = gson.fromJson(response, EvaluateDetailBean.class);
                if (model.isSuccess()) {
                    getEvaluateData(model.getData());
                }
            }
        });
    }

    private void getCourse(String startrow) {
        String loginUrl = Constant.URL_TEACHER + "EvaluateTeacher/TeacherCustomEvaluation";
        HashMap<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("teacherId", GetUserInfo.getTeacherId(getActivity()));
        map.put("operatorType", "教师");
        map.put("operatorId", GetUserInfo.getTeacherId(getActivity()));
        map.put("token", GetUserInfo.getToken(getActivity()));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                swipeRefreshWidget.setRefreshing(false);
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        isLoading = true;
                        adapterCustom.setHasMore(false);
                        adapterCustom.notifyDataSetChanged();
                        swipeRefreshWidget.setRefreshing(false);
                        adapterCustom.notifyItemRemoved(adapterCustom.getItemCount());
                        ToastUtil.showToast(getActivity(), jsonObject.getString("message"));
                        return;
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                EvaluateCustomBean model = gson.fromJson(response, EvaluateCustomBean.class);
                if (model.isSuccess()) {
                    if (model.getData().getList().size() < 10) {
                        isLoading = true;
                        adapterCustom.setHasMore(false);
                    } else {
                        isLoading = false;
                        adapterCustom.setHasMore(true);
                    }

                    customData.addAll(model.getData().getList());
                    bean = model.getData();
                    adapterCustom.setEvaluateTeacher(bean);
                    adapterCustom.notifyDataSetChanged();
                    swipeRefreshWidget.setRefreshing(false);
                    adapterCustom.notifyItemRemoved(adapterCustom.getItemCount());
                }
            }
        });
    }


}
